<template>
  <div class="page goods-data-list">
    <mt-datetime-picker
      v-if="startPickerVisible"
      ref="startPicker"
      class="date-timer-picker"
      type="date"
      v-model="startDate"
      year-format="{value}年"
      month-format="{value}月"
      date-format="{value}日"
      confirmText="下一步"
      @confirm="endPicker"
      @cancel="cancelPicker"
      :startDate="startDateScope"
      :endDate="endDateScope"
    ></mt-datetime-picker>
    <mt-datetime-picker
      v-if="endPickerVisible"
      ref="endPicker"
      type="date"
      class="date-timer-picker"
      v-model="endDate"
      year-format="{value}年"
      month-format="{value}月"
      date-format="{value}日"
      :startDate="startDateScope2"
      :endDate="endDateScope"
      @confirm="dateChoice"
      @cancel="cancelPicker"
    ></mt-datetime-picker>
    <StoreChoice
      ref="StoreChoice"
      :current="[]"
      :multipleChoice="false"
      @listenToStoreSelect="getSelectStoreValue"
      :hasTotal="true"
      reqUrl="/newapp/shop/getMarketShopSelect.do"
    />
    <div class="scroll-view">
      <customHeader
        middleTitle="商品数据看板"
        rightTitle="商品管理"
        @leftCallBack="handleBack"
        @rightCallBack="linkToManage"
      />
      <div class="page-body">
        <ul class="filter-box">
          <li @click="handleClickSelectStore">
            <span>门店：{{storeName}}</span>
            <i v-if="roleInfo.manyShopFlag" class="zhk-list_rarrow"></i>
          </li>
          <li @click="startPicker">
            <span>时间：{{formateDate(startDate)}} 至 {{formateDate(endDate)}}</span>

            <i class="zhk-list_rarrow"></i>
          </li>
        </ul>
        <ul class="list-box">
          <li>
            <div class="middle">
              <div class="middle-title">整体概览</div>
              <ul class="board-list">
                <li>
                  <span>成交用户(人)</span>
                  <div>{{data['dealUserVolume']}}</div>
                </li>
                <li>
                  <span>实收金额(元)</span>
                  <div>{{data['receiveAmount']}}</div>
                </li>
                <li>
                  <span>退款金额(元)</span>
                  <div>{{data['refundAmount']}}</div>
                </li>
              </ul>
              <ul class="board-list">
                <li>
                  <span>销量(份)</span>
                  <div>{{data['salesVolume']}}</div>
                </li>
                <li>
                  <span>核销(份)</span>
                  <div>{{data['writeOff']}}</div>
                </li>
                <li>
                  <span>退款(份)</span>
                  <div>{{data['refundVolume']}}</div>
                </li>
              </ul>
            </div>
            <div class="bottom">
              <div class="btn" @click="linkToSingle">
                按商品看数据
                <i class="zhk-list_rarrow"></i>
              </div>
              <div class="btn" @click="linkToRecord">
                核销记录
                <i class="zhk-list_rarrow"></i>
              </div>
            </div>
          </li>
        </ul>
        <div class="chart-box">
          <div class="title">
            交易趋势
            <InfoModal icon="zhk-ts" infoTitle="说明" :infoText="['默认为截止昨日数据，不随已选时间变化']" />
          </div>
          <ul class="tab-chart">
            <li
              v-for="(item,index) in tabList"
              :key="index"
              :class="{'active':item.value==curTab}"
              @click="handleTabChange(item.value)"
            >{{item.label}}</li>
          </ul>
          <div class="line-wrap">
            <ve-line :data="chartData" :settings="chartSettings"></ve-line>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue';
import customHeader from '../../components/header/header';
import noData from "../../components/noData/noData";
import StoreChoice from "../../components/StoreChoice/StoreChoice";
import jsAuthority from "../../tools/jsAuthority.js";
import { Toast, DatetimePicker, Popup } from 'mint-ui';
import InfoModal from "../../components/InfoModal/InfoModal";
import jsBridge from '../../tools/jsBridge.js';
Vue.component(Popup.name, Popup);
import moment from "moment";
export default {
  name: 'goodsDataBoard',
  data() {
    this.chartSettings = {
      axisSite: { right: ['销量'] },
      yAxisName: ['实收金额(元)', '销量'],
    }
    return {
      storeName: "全部门店",
      shopId: [],
      curTab: 7,
      tabList: [{ label: "近7天", value: 7 }, { label: "近30天", value: 30 }],
      chartData: {
        columns: ["日期", "实收金额", "销量"],
        rows: [
          // { "日期": "1-1", "实收金额": 110, "销量": 21 },
          // { "日期": "1-2", "实收金额": 120, "销量": 22 },
          // { "日期": "1-3", "实收金额": 130, "销量": 23 },
          // { "日期": "1-4", "实收金额": 150, "销量": 24 },
          // { "日期": "1-5", "实收金额": 170, "销量": 25 },
          // { "日期": "1-6", "实收金额": 190, "销量": 26 },
          // { "日期": "1-7", "实收金额": 220, "销量": 27 },
        ]
      },
      startDate: new Date(moment().millisecond(0).second(0).minute(0).hour(0)),
      endDate: new Date(),
      startPickerVisible: false,
      endPickerVisible: false,
      startDateScope: new Date(new Date() - 1000 * 60 * 60 * 24 * 180), //可选开始日期范围
      startDateScope2: new Date(), //可选结束日期范围
      endDateScope: new Date(),
      loading: false,
      data: {},
      list: [],
      roleInfo: {},
      authScan: false,
    };
  },
  methods: {
    handleBack() {
      if (this.$refs.StoreChoice && this.$refs.StoreChoice.popupVisible) {
        this.$refs.StoreChoice.back();
      } else {
        if (String(this.$route.query.close) == 'true') {
          jsBridge.closeWindow();
        } else {
          this.$router.back();
        }
      }
    },
    handleTabChange(v) {
      this.curTab = v;
      this.getChartData();
    },
    formateDate(date) {
      if (typeof date == "object") {
        return moment(date).format("YYYY-MM-DD");
      } else {
        return date;
      }
    },
    //日期选择展开
    startPicker() {
      this.startPickerVisible = true;
      this.endPickerVisible = true;
      this.endDateScope = new Date();
      this.$nextTick(() => {
        this.$refs.startPicker.open();
      });
    },
    //结束日期展开
    endPicker(e) {
      this.startDateScope2 = e;

      //日期选择范围为31天且不超过当前时间
      if (new Date().valueOf() - e.valueOf() > 31 * 24 * 3600 * 1000) {
        this.endDateScope = new Date(e.valueOf() + 31 * 24 * 3600 * 1000);
      } else {
        this.endDateScope = new Date();
      }

      this.$nextTick(() => {
        this.$refs.endPicker.open();
      });
    },
    //结束日期选择
    dateChoice(e) {
      this.startPickerVisible = false;
      this.endPickerVisible = false;
      this.getData();
    },
    //点取消关闭日期组件
    cancelPicker() {
      this.startPickerVisible = false;
      this.endPickerVisible = false;
    },
    handleClickSelectStore() {
      this.$refs.StoreChoice.popupShow();
    },
    getSelectStoreValue(value, storeName) {
      var shopId = value[0].selectKey;
      this.shopId =shopId=="all"?[]:[shopId];
      this.storeName = storeName;
      this.getData(this.getChartData);
    },
    getData(func) {
      const url = "/newapp/mall/board/queryMallStatistics.do";
      const params = { shopIdList: this.shopId ? this.shopId : [], startDate: moment(this.startDate).format("YYYYMMDD"), endDate: moment(this.endDate).format("YYYYMMDD") };
      this.ajax({
        url: url,
        type: "post",
        data: params,
        controlLoading: true
      })
        .then(res => {
          func && func();
          if (res.success) {
            this.data = res.resultObject;
          } else {
            Toast(res.msg);
          }
        })
        .catch((err) => {

        });
    },
    getChartData() {
      let startDate;
      let endDate = moment().subtract(1, 'days');
      if (this.curTab == 30) {
        startDate = moment(endDate).subtract(30 - 1, 'days');
      } else {
        startDate = moment(endDate).subtract(7 - 1, 'days');
      }
      const url = "/newapp/mall/board/queryMallStatisticsTrend.do";
      const params = { shopIdList: this.shopId ? this.shopId : [], startDate: moment(startDate).format("YYYYMMDD"), endDate: moment(endDate).format("YYYYMMDD") };
      this.ajax({
        url: url,
        type: "post",
        data: params,
        controlLoading: false
      })
        .then(res => {
          if (res.success) {
            const data = res.resultObject;
            const row = data.map((item) => {
              let m = "";
              if (String(item.bizDate).length > 4) {
                const md = String(item.bizDate).substr(4, 4);
                m = md.slice(0, 2) + "-" + md.slice(2);
              }

              return { "日期": m, "实收金额": item.receiveAmount, "销量": item.salesVolume }
            });
            if(row.length){
              this.chartData.rows = row;
            }else{
              this.chartData.rows = [{ "日期": "-", "实收金额": 0, "销量": 0 }];
            }
          } else {
            Toast(res.msg);
          }
        })
        .catch((err) => {

        });
    },
    linkToSingle() {
      const shopId=this.shopId;
      this.$router.push({ path: '/goodsDataBoard/single', query: { type: 0, startDate:this.startDate.valueOf(),endDate:this.endDate.valueOf(),shopId:shopId,shopName:this.storeName} });
    },
    linkToRecord() {
       const shopId=this.shopId;
      this.$router.push({ path: '/cancelVerifi/cancelVerifiList', query: {startDate:this.startDate.valueOf(),endDate:this.endDate.valueOf(),shopId:shopId,shopName:this.storeName} });
    },
    linkToManage() {
      if (!this.authScan) {
        Toast("暂无权限");
        return;
      }
      this.$router.push({ path: '/goodsDataBoard/goodsManage' });
    },
    getAuth() {
      jsAuthority.checkedSuccess(() => {
        this.authScan = jsAuthority.checked(
          "app.goodsManage.scan"
        );

      });
    }
  },
  components: {
    customHeader,
    noData,
    StoreChoice,
    InfoModal
  },
  created() {
    this.getAuth();
    CommonUtil.getUserInfo().then(userInfo => {
      this.roleInfo = userInfo;
      if (!this.roleInfo.manyShopFlag) {
        this.shopId = [this.roleInfo.yzShopId];
        this.storeName = this.roleInfo.shopName;
      }
      this.getData(this.getChartData);
    });
  },
};
</script>
<style lang='scss' scoped>
@import "goodsDataBoard";
</style>
